from django.shortcuts import render, redirect

# Create your views here.
from app02 import models
from app02.utils.form import UserModelForm, PrettyModelForm
from app02.utils.pagination import Pagination


def pretty_list(request):
    # for i in range(9):
    #     models.PrettyNum.objects.create(mobile=f"1821111111{i}",price=i,level=1,status=1)
    #靓号列表
    data_dict = {}
    search_data = request.GET.get("q","")
    if search_data:
        data_dict["mobile__contains"] = search_data
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    page_object = Pagination(request,queryset)
    context = {
        "search_data":search_data,
        "queryset":page_object.page_queryset,
        "page_string":page_object.html()
    }
    #queryset = models.PrettyNum.objects.all().order_by("-level")
    return render(request,"pretty_list.html",context)


def pretty_add(request):
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request,"pretty_add.html",{"form":form})
    form = PrettyModelForm(data = request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request,"pretty_add.html",{"form":form})

def pretty_edit(request,nid):
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    #根据id获取数据
    if request.method=='GET':
        form = PrettyModelForm(instance=row_object)
        return render(request,"pretty_edit.html",{"form": form})

    form = PrettyModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据，如果想要再用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/pretty/list/')
    return render(request,'pretty_edit.html',{'form',form})

def pretty_delete(request, nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')
